<template>
  <!-- 弹窗 -->
  <el-dialog
    v-model="batch_import_data.show"
    title="批量导入奖项"
    width="512px"
    @closed="handleClosed"
  >
    <div v-if="batch_import_data.step==0">

      <el-form label-width="120px">
        <el-form-item label="选择导入文件">
          <div style="width:320px">
            <el-upload
              drag
              :before-upload="beforeAvatarUpload"
              :action="UploadUrl"
              :show-file-list="false"
              accept=".xlsx"
              v-loading="batch_import_data.file_loading"
            >
              <div v-if="!batch_import_data.upload_state">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件或 <em>点击上传</em>
                </div>
              </div>
              <div v-else>
                <el-icon class="el-icon--upload">
                  <Document />
                </el-icon>
                <div class="el-upload__text">
                  <el-text>
                    已上传，准备导入数量：{{batch_import_data.data.length}}
                  </el-text>
                </div>
              </div>
            </el-upload>
            <el-space>
              <el-text size="small">文件支持格式：.xlsx </el-text>
              <!-- href="/public/static/file/awardTemp.xlsx" -->
              <el-link
                size="small"
                type="primary"
                @click="handleDownTempFile"
              >下载模板</el-link>
            </el-space>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            size="large"
            @click="batch_import_data.show=false"
          >取消</el-button>
          <el-button
            size="large"
            type="primary"
            :loading="batch_import_data.api_loading"
            @click="handleBatchImportIntegral"
          >导入</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else-if="batch_import_data.step==1">
      <el-result
        icon="success"
        title="导入结束"
        :sub-title="'总共导入数量'+batch_import_data.data.length+'人，成功'+batch_import_data.res.successNumber+'人，失败'+batch_import_data.res.failNumber+'人。'"
      >
        <!-- :sub-title="'总共导入数量'+batch_import_data.data.integral.length+'份'" -->
        <template #extra>
          <el-button
            size="large"
            @click="batch_import_data.step=0"
          >重新导入</el-button>
          <!-- <el-button
            size="large"
            type="warning"
          >详情</el-button> -->
          <el-button
            size="large"
            type="info"
            @click="batch_import_data.show=false"
          >关闭</el-button>
        </template>
      </el-result>
    </div>
  </el-dialog>
</template>

<script  setup>
import { ref } from "vue"
import { read, writeFile, utils } from 'xlsx'
import { saveAs } from 'file-saver';
import { ElMessage, ElNotification } from "element-plus";
import { ImportAwards } from "@/api";
const emit = defineEmits(['close'])
const Authorization = localStorage.getItem('token') ? localStorage.getItem('token') : "";
const baseURL = import.meta.env.VITE_MODE != 'dev' ? import.meta.env.VITE_API_HOST : '/api'
const UploadUrl = baseURL + "/api/uploadFile"
const batch_import_data = ref({
  show: false,
  file_loading: false,
  api_loading: false,
  upload_state: false,
  step: 0,
  data: {
    // integral: [],
  },
  res: {

  }
})
/**
 * 上传前
 */
const beforeAvatarUpload = (rawFile) => {
  const type_arr = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
  if (!type_arr.includes(rawFile.type)) {
    ElMessage.error('文件格式不正确!')
    return false
  }
  const size = 5;
  if (rawFile.size / 1024 / 1024 > size) {
    ElMessage.error('上传大小不得超过 ' + size + 'M')
    return false
  }
  handleFileToData(rawFile);
  //  读取文件
  return false
}
/**
 * 处理上传文件
 */
const handleFileToData = (file) => {
  batch_import_data.value.file_loading = true;
  const reader = new FileReader()
  reader.onload = (e) => {
    const { result } = e.target
    try {
      const workbook = read(result, { type: 'binary' })
      const json_data = utils.sheet_to_json(workbook.Sheets['奖项']);
      batch_import_data.value.data = json_data.map((item) => {
        return {
          studentId: item['ID'],
          awards: item['奖项'] ?? null,
        }
      }).filter((item) => {
        return item.studentId
      })
      batch_import_data.value.upload_state = true;

    } catch (error) {

    }
    batch_import_data.value.file_loading = false;

  }
  reader.onerror = () => {
    batch_import_data.value.file_loading = false;
  }
  //   reader.readAsBinaryString(file)
  reader.readAsArrayBuffer(file)
}
/**
 * 下载上传模板
 */
// const handleDownTempFile = () => {
//   // 定义下拉选项
//   const dataValidation = {
//     sqref: 'B2:B100', // 设置下拉选项的范围
//     type: 'list',
//     allowBlank: true,
//     formula1: '"一等奖,二等奖,三等奖,优秀奖"', // 注意，这里的选项需要使用双引号包裹
//   };
//   const data = [
//     ['ID', '奖项'],
//     [1, ''],
//     [2, ''],
//     [3, ''],
//     [4, ''],
//   ];
//   // 新建空workbook，然后加入worksheet
//   console.log(data);
//   const ws = utils.json_to_sheet(data)
//   // 将数据验证应用于工作表的相应单元格
//   ws['!dataValidation'] = [dataValidation];
//   // 设置每列的列宽，10代表10个字符，注意中文占2个字符
//   ws['!cols'] = [
//     { wch: 10 },
//     { wch: 30 },
//     { wch: 25 }
//   ]
//   // 新建book
//   const wb = utils.book_new()
//   // 生成xlsx文件(book,sheet数据,sheet命名)
//   utils.book_append_sheet(wb, ws, '奖项')
//   // 写文件(book,xlsx文件名称)
//   let blob = writeFile(wb, '批量导入奖项模板.xlsx')
//   //   let blob = new Blob(text_data, { type: "text/csv;charset=utf-8" });
//   ElMessage.success("正在导出");
//   saveAs(blob);
// }

/**
 * 下载上传模板
 */
const handleDownTempFile = async () => {
  // 初始化
  const wb = new ExcelJS.Workbook();
  const Sheet1 = wb.addWorksheet('奖项');
  // const Sheet2 = wb.addWorksheet('奖项内容');
  // const test = wb.addWorksheet('test');

  // 导出的内容
  Sheet1.columns = [
    // A1
    {
      header: 'ID',
      key: 'no',
      width: 20
    },
    // B2
    {
      header: '奖项',
      key: 'sex',
      width: 20
    },
  ];
  // 默认数据
  const Sheet1_data = [{
    no: '10001',
    sex: '一等奖',
  }]
  Sheet1.addRows(Sheet1_data);
  new Array(1000).fill(0).forEach((_, idx) => {
    const row = idx + 2;
    // 渲染部门下拉框
    Sheet1.getCell(row, 2).dataValidation = {
      type: 'list',
      formulae: [`"一等奖, 二等奖, 三等奖, 优秀奖"`]
    };
  });

  // 导出格式...
  const buffer = await wb.xlsx.writeBuffer();
  var blob = new Blob([buffer], {
    type: "application/octet-stream"
  });
  // 设定导出名字
  var url = blob, saveName = '批量导入奖项模板.xlsx';
  if (typeof url == 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url); // 创建blob地址
  }
  var aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = saveName || '';
  var event;
  if (window.MouseEvent) event = new MouseEvent('click');
  else {
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0,
      null);
  }
  aLink.dispatchEvent(event);
  console.log(111)
  return;
}

/**
 * 开始导入
 */
const handleBatchImportIntegral = async () => {
  batch_import_data.value.api_loading = true;
  let res = await ImportAwards(batch_import_data.value.data)
  if (res.success) {
    ElNotification({
      title: '成功',
      message: res.message,
      type: 'success',
    })
    batch_import_data.value.step = 1
    batch_import_data.value.res = res.entity;
  } else {
    ElMessage.error(res.message)
  }
  batch_import_data.value.api_loading = false;
}
/**
 * 打开批量导入积分的弹窗
 */
const handleOpenModal = () => {
  batch_import_data.value.show = true;
  batch_import_data.value.step = 0;
  batch_import_data.value.upload_state = false;
  batch_import_data.value.data.integral = [];
  // batch_import_data.value.data.type = 3;
}
const handleClosed = () => {
  emit('closed')
}
defineExpose({
  handleOpenModal
})
</script>

<style lang="scss" scoped></style>